package 网络编程.TCPECHO;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-10-04
 * Time: 22:24
 */
public class TCPEchoServer1 {
    //使用字节流不使用scanner进行转换
    private ServerSocket serverSocket = null;
    public TCPEchoServer1(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        //服务器监听8000端口是否有连接.
        //服务器没有接收到连接之前一直阻塞等待,客户端建立连接,就把连接返回给socket对象
        System.out.println("服务端正在监听8000端口...");
        Socket socket = serverSocket.accept();
        //然后服务端这边接收到连接,给socket对象,然后通过socket对象进行与客户端进行交互
        processService(socket);
    }

    public void processService(Socket socket) throws IOException {
        System.out.println("服务器开始启动!!!");
        System.out.printf("建立连接[%s:%d]\n",socket.getInetAddress().toString()
                ,socket.getPort());
        int readLn = 0;
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            while(true){
                //服务器这边读取客户端的请求
                byte[] bytes = new byte[1024];
                String request = "";
                while((readLn=inputStream.read(bytes))!=-1){
                    request = new String(bytes,0,readLn);
                }
                //构造响应
                String response = process();
                //将响应发送给客户端
                outputStream.write(response.getBytes());
                socket.shutdownOutput();
                System.out.printf("[%s:%d] req = %s;rep = %s\n",socket.getInetAddress().toString()
                        ,socket.getPort(),request,response);
            }
        }finally {
            socket.close();
        }
    }

    public static String process(){
        return "hello,clint";
    }

    public static void main(String[] args) throws IOException {
        TCPEchoServer1 tcpEchoServer1 = new TCPEchoServer1(8000);
        tcpEchoServer1.start();
    }

}
